<?php

namespace App\Models;

class Area extends Base
{
    // 表名
    protected $table = 'areas';

    public function allChildren() {
        $type = request()->type??2;
        $otherIds = [];
        if($type==1){
            $ids = Community::where(['is_deleted'=>0,'status'=>1])->select('city','area')->get()->toArray();
            $otherIds = array_unique(array_merge(array_column($ids,'city'),array_column($ids,'area'))); //城市和区县的id集合
        }
        return $this->hasMany(Area::class, 'pid', 'code')
            ->where(function($query) use ($otherIds){
                //如果有城市和区县id集合时，只查对应的数据
                if($otherIds){
                    $query->whereIn('id',$otherIds);
                }
            })
            ->select('id as value','name as label','code','pid');
    }

    public function children()
    {
        return $this->allChildren()->with('children');
    }
}
